package com.catazy.ocrdemo.ui.activity.scan

import android.graphics.Bitmap
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.catazy.mvvmlib.base.activity.BaseVmVbActivity
import com.catazy.ocrdemo.R
import com.catazy.ocrdemo.databinding.ActivityScanBinding
import com.catazy.ocrdemo.entity.ScanResult
import com.catazy.ocrdemo.ui.activity.scan.fragment.crop.ImageCropFragment
import com.catazy.ocrdemo.ui.activity.scan.fragment.ScanFragment
import com.catazy.ocrdemo.ui.activity.scan.fragment.process.ImageProcessFragment

/**
 * 作者: Tao
 * 日期: 2024/3/7
 * 时间: 17:47
 * 描述: 扫描页面 BaseVmVbActivity<AppScanViewModel, ActivityScanBinding>()
 */
class AppScanActivity : BaseVmVbActivity<AppScanViewModel, ActivityScanBinding>() {


    companion object {
        private const val ORIGINAL_IMAGE_NAME = "original"
        internal const val SCAN_FRAGMENT_TAG = "ScanFragmentTag"
        internal const val CROP_FRAGMENT_TAG = "CropFragmentTag"
        internal const val PROCESS_FRAGMENT_TAG = "ProcessFragmentTag"
    }

    private var scanResult: ScanResult? = null
    private var croppedImage: Bitmap? = null

    override fun initView(savedInstanceState: Bundle?) {
        showScanFragment()
    }

    /**
     * 显示扫描页面
     */
    fun showScanFragment() {
        val fragment = ScanFragment()
        addFragmentToBackStack(fragment, SCAN_FRAGMENT_TAG)
    }

    /**
     * 显示图片裁剪页面
     */
    fun showImageCropFragment() {
        val fragment = ImageCropFragment()
        addFragmentToBackStack(fragment, CROP_FRAGMENT_TAG)
    }

    fun showImageProcessFragment() {
        val fragment = ImageProcessFragment()
        addFragmentToBackStack(fragment, PROCESS_FRAGMENT_TAG)
    }

    fun closeFragment() {
        supportFragmentManager.popBackStackImmediate()
    }

    /**
     * 设置扫描结果
     */
    fun setScanResult(result: ScanResult) {
        scanResult = result
    }

    /**
     * 获取扫描结果
     */
    fun getScanResult(): ScanResult? {
        return scanResult
    }

    fun setCroppedImage(bitmap: Bitmap) {
        croppedImage = bitmap
    }

    fun getCroppedImage(): Bitmap? {
        return croppedImage
    }

    private fun addFragmentToBackStack(fragment: Fragment, fragmentTag: String) {
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.scanContainer, fragment, fragmentTag)
        if (supportFragmentManager.findFragmentByTag(fragmentTag) == null) {
            fragmentTransaction.addToBackStack(fragmentTag)
        }
        fragmentTransaction.commit()
    }
}